class Director {
    constructor(fps, runCallback) {
        window.Sid = 0
        window.Lid = 0
        window.Aid = 0
        window.paused = false
        //canvas获取
        this.canvas = document.querySelector('#m_canvas')
        this.ctx = this.canvas.getContext('2d')
        this.height = 600
        this.width = 800
        //事件容器
        this.actions = {}
        this.state = {}

        //数据初始化
        this.instance = this
        this.scene = null
        window.fps = fps
        this.runCallback = runCallback
        //监听键盘输入
        window.addEventListener('keydown', event => {
            this.state[event.key] = 'down'
        })
        window.addEventListener('keyup', event => {
            this.state[event.key] = 'up'
        })
        this.start()

    }
    //传递dir
    static instance(...args) {
        this.i = this.i || new this(...args)
        return this.i
    }
    start() {
        this.runCallback(this)
    }
    replaceScene(scene) {
        this.scene = scene
    }
    registerAction(key, callback) {
        this.actions[key] = callback
    }
    drawImage(sprite,x,y) {
        this.ctx.drawImage(sprite.image, x, y)
    }
    drawNode(node) {
        var g = this
        var map = {
            'Sprite': function (sprite) {
                g.ctx.drawImage(sprite.image, sprite.x, sprite.y)
            },
            'Label': function (label) {
                g.ctx.drawImage(sprite.image, sprite.x, sprite.y)
            },
            'Animation': function (sprite) {
                g.ctx.drawImage(sprite.image, sprite.x, sprite.y)
            },
        }
        map[node.type](node)
    }
    runWithScene(scene) {
        this.scene = scene
        setTimeout(() => {
            this.runLoop()
        }, 1000 / window.fps);
    }
    runLoop() {
        var acName = Object.keys(this.actions)
        for (var i = 0; i < acName.length; i++) {
            var key = acName[i]
            if (this.state[key]=='down') {
                this.actions[key](this.state[key])
            }else if(this.state[key]=='up'){
                this.actions[key](this.state[key])
                this.state[key]=null
            }
        }
        this.update()
        this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height)
        this.draw()
        setTimeout(() => {
            this.runLoop()
        }, 1000 / window.fps);
    }
    draw() {
        this.scene.draw()
    }
    update() {
        this.scene.update()
    }
}